<?php
namespace app\common\controller;
require_once __DIR__.'/../../../vendor/autoload.php';

use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Config;
use Exception;
use think\facade\Log;

/**
 * 支付宝支付封装类
 */
class Alipay
{
    /**
     * 支付宝配置
     */
    private static $config = null;
    
    /**
     * 初始化支付宝SDK
     */
    public static function init()
    {
        if (self::$config !== null) {
            return;
        }
        
        // 获取配置
        $alipayConfig = config('alipay.');
        if (empty($alipayConfig)) {
            throw new Exception('支付宝配置不能为空');
        }
        
        // 创建配置对象
        self::$config = new Config();
        self::$config->protocol = $alipayConfig['protocol'];
        self::$config->gatewayHost = $alipayConfig['gatewayHost'];
        self::$config->signType = $alipayConfig['signType'];
        
        // 设置应用ID和私钥
        self::$config->appId = $alipayConfig['appId'];
        self::$config->merchantPrivateKey = $alipayConfig['merchantPrivateKey'];
        
        // 判断是否使用证书模式
        if (!empty($alipayConfig['alipayCertPath']) 
            && !empty($alipayConfig['alipayRootCertPath']) 
            && !empty($alipayConfig['merchantCertPath'])) {
            self::$config->alipayCertPath = $alipayConfig['alipayCertPath'];
            self::$config->alipayRootCertPath = $alipayConfig['alipayRootCertPath'];
            self::$config->merchantCertPath = $alipayConfig['merchantCertPath'];
        } else {
            self::$config->alipayPublicKey = $alipayConfig['alipayPublicKey'];
        }
        
        // 设置异步通知地址
        if (!empty($alipayConfig['notifyUrl'])) {
            self::$config->notifyUrl = $alipayConfig['notifyUrl'];
        }
        
        // 设置AES密钥
        if (!empty($alipayConfig['encryptKey'])) {
            self::$config->encryptKey = $alipayConfig['encryptKey'];
        }
        
        // 设置支付宝SDK配置
        Factory::setOptions(self::$config);
    }
    
    /**
     * WAP支付
     * @param array $params 支付参数
     * @return array
     */
    public static function wapPay($params,$notify_url="")
    {
        try {
            // 初始化SDK
            self::init();
            // 必传参数校验
            if (empty($params['subject']) || empty($params['out_trade_no']) || empty($params['total_amount'])
                || empty($params['quit_url']) || empty($params['return_url'])) {
                return ['code' => 0, 'msg' => '缺少必要的支付参数'];
            }

            // 构建支付参数
            $subject = $params['subject']; // 商品标题
            $outTradeNo = $params['out_trade_no']; // 商户订单号
            $totalAmount = $params['total_amount']; // 订单总金额

            // 可选参数
            $quitUrl = $params['quit_url'] ?? ''; // 用户付款中途退出返回商户网站的地址
            // 调用支付宝WAP支付接口
            $returnUrl = $params['return_url'] ?? '';
            $result = Factory::payment()->wap()->asyncNotify($notify_url)->pay($subject, $outTradeNo, $totalAmount, $quitUrl, $returnUrl);
            // 返回支付表单
            return [
                'code' => 1,
                'msg' => 'success',
                'data' => $result->body,
                'order_no' => $outTradeNo,
            ];
        } catch (Exception $e) {
            Log::error('支付宝WAP支付异常: ' . $e->getMessage());
            return [
                'code' => -1,
                'msg' => '支付创建异常: ' . $e->getMessage(),
                'data' => null
            ];
        }
    }
    public static function appPay($params,$notify_url="")
    {
        try {
            // 初始化SDK
            self::init();
            // 必传参数校验
            if (empty($params['subject']) || empty($params['out_trade_no']) || empty($params['total_amount'])
                || empty($params['quit_url']) || empty($params['return_url'])) {
                return ['code' => 0, 'msg' => '缺少必要的支付参数'];
            }

            // 构建支付参数
            $subject = $params['subject']; // 商品标题
            $outTradeNo = $params['out_trade_no']; // 商户订单号
            $totalAmount = $params['total_amount']; // 订单总金额

            // 可选参数
            $quitUrl = $params['quit_url'] ?? ''; // 用户付款中途退出返回商户网站的地址
            // 调用支付宝WAP支付接口
            $returnUrl = $params['return_url'] ?? '';
            $result = Factory::payment()->app()->asyncNotify($notify_url)->pay($subject, $outTradeNo, $totalAmount, $quitUrl, $returnUrl);
            // 返回支付表单
            return [
                'code' => 1,
                'msg' => 'success',
                'data' => $result->body,
                'order_no' => $outTradeNo,
            ];
        } catch (Exception $e) {
            Log::error('支付宝WAP支付异常: ' . $e->getMessage());
            return [
                'code' => -1,
                'msg' => '支付创建异常: ' . $e->getMessage(),
                'data' => null
            ];
        }
    }


    /**
     * 将支付表单转换为URL
     */
    public static function convertFormToUrl($formHtml)
    {
        $doc = new \DOMDocument();
        @$doc->loadHTML($formHtml);

        $form = $doc->getElementsByTagName('form')->item(0);
        $action = $form->getAttribute('action');

        $params = [];
        foreach ($form->getElementsByTagName('input') as $input) {
            $params[$input->getAttribute('name')] = $input->getAttribute('value');
        }

        return $action . '?' . http_build_query($params);
    }
    /**
     * 查询交易
     * @param string $outTradeNo 商户订单号
     * @return array
     */
    public static function query($outTradeNo)
    {
        try {
            // 初始化SDK
            self::init();
            
            // 调用交易查询接口
            $result = Factory::payment()->common()->query($outTradeNo);
            
            if (!empty($result->code) && $result->code == 10000) {
                return [
                    'code' => 1,
                    'msg' => '查询成功',
                    'data' => [
                        'trade_no' => $result->tradeNo, // 支付宝交易号
                        'out_trade_no' => $result->outTradeNo, // 商户订单号
                        'trade_status' => $result->tradeStatus, // 交易状态
                        'total_amount' => $result->totalAmount, // 订单金额
                        'buyer_id' => $result->buyerUserId, // 买家支付宝用户号
                        'gmt_payment' => $result->sendPayDate, // 支付时间
                    ]
                ];
            } else {
                return [
                    'code' => 0,
                    'msg' => '查询失败: ' . ($result->msg ?? '') . ', ' . ($result->subMsg ?? ''),
                    'data' => null
                ];
            }
        } catch (Exception $e) {
            Log::error('支付宝交易查询异常: ' . $e->getMessage());
            return [
                'code' => -1,
                'msg' => '查询异常: ' . $e->getMessage(),
                'data' => null
            ];
        }
    }
    
    /**
     * 关闭交易
     * @param string $outTradeNo 商户订单号
     * @return array
     */
    public static function close($outTradeNo)
    {
        try {
            // 初始化SDK
            self::init();
            
            // 调用交易关闭接口
            $result = Factory::payment()->common()->close($outTradeNo);
            
            if (!empty($result->code) && $result->code == 10000) {
                return [
                    'code' => 1,
                    'msg' => '交易关闭成功',
                    'data' => null
                ];
            } else {
                return [
                    'code' => 0,
                    'msg' => '交易关闭失败: ' . ($result->msg ?? '') . ', ' . ($result->subMsg ?? ''),
                    'data' => null
                ];
            }
        } catch (Exception $e) {
            Log::error('支付宝交易关闭异常: ' . $e->getMessage());
            return [
                'code' => -1,
                'msg' => '关闭异常: ' . $e->getMessage(),
                'data' => null
            ];
        }
    }
    
    /**
     * 验证异步通知
     * @param array $params 通知参数
     * @return bool
     */
    public static function verifyNotify($params)
    {
        try {
            // 初始化SDK
            self::init();
            
            // 验证签名
            $result = Factory::payment()->common()->verifyNotify($params);
            return $result;
        } catch (Exception $e) {
            Log::error('支付宝异步通知验证异常: ' . $e->getMessage());
            return false;
        }
    }
}